package demo.tcpClient;

import net.jueb.protoServer.handler.codec.impl.ProtoMessageDecoderHandler;
import net.jueb.protoServer.handler.codec.impl.ProtoMessageEncoderHandler;
import net.jueb.protoServer.handler.codec.impl.ProtoMessagePackHandler;
import net.jueb.protoServer.handler.codec.impl.ProtoMessageUnPackHandler;
import net.jueb.protoServer.message.ProtoMessage;

import com.google.protobuf.ExtensionRegistry;

import demo.protocol.MessageTestProto;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TcpClient {
	NioEventLoopGroup group=new NioEventLoopGroup();
	Bootstrap bt=new Bootstrap();
	
	
	public TcpClient() {
		bt.group(group);
		bt.channel(NioSocketChannel.class);
		bt.handler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				System.out.println(sc.localAddress());
				System.out.println(sc.remoteAddress());
				//指定类型的解码器
				//扩展类型注册器
				ExtensionRegistry registry = ExtensionRegistry.newInstance();
				ProtoMessage.registerAllExtensions(registry);//注册所有扩展类型
				MessageTestProto.registerAllExtensions(registry);//注册测试扩展消息类型
				//以Message为解码主体
				sc.pipeline().addLast(new ProtoMessageUnPackHandler());
				sc.pipeline().addLast(new ProtoMessageDecoderHandler(ProtoMessage.Message.getDefaultInstance(), registry));
				sc.pipeline().addLast(new ProtoMessagePackHandler());
				sc.pipeline().addLast(new ProtoMessageEncoderHandler());
				//加入业务处理
				sc.pipeline().addLast(new TcpClientHandler());
			}
		});
	}
	
	public Channel connect(final String ip,final int port) throws InterruptedException
	{
		final Channel channel=bt.connect(ip, port).sync().channel();
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					channel.closeFuture().sync();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}finally{
					group.shutdownGracefully();
				}
			}
		}).start();
		return channel;
	}
	public static void main(String[] args) throws InterruptedException {
		TcpClient t=new TcpClient();
		for(int i=0;i<1000;i++)
		{
			t.connect("127.0.0.1",1111);
			Thread.sleep(900);
		}
		Thread.sleep(1000000);
	}
}
